package com.yfbao.poll.demo.service;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询相关线程池定义类
 */
public final class PollingExecutor {

    //长轮询延时处理线程池
    private static ScheduledExecutorService LONG_POLLING_EXECUTOR = Executors.newScheduledThreadPool(1,new NameThreadFactory("long-poll-executor"));

    //普通任务异步延时处理线程池
    private static ScheduledExecutorService NORMAL_EXECUTOR = Executors.newScheduledThreadPool(1,new NameThreadFactory("poll-normal-executor"));


    public static ScheduledFuture<?> scheduleLongPolling(Runnable runnable, long delay, TimeUnit unit) {
        return LONG_POLLING_EXECUTOR.schedule(runnable, delay, unit);
    }

    public static ScheduledFuture<?> scheduleNormalTask(Runnable runnable, long delay, TimeUnit unit) {
        return NORMAL_EXECUTOR.schedule(runnable, delay, unit);
    }

    public static void executeNormalTask(Runnable runnable) {
        NORMAL_EXECUTOR.execute(runnable);
    }


    public static class NameThreadFactory implements ThreadFactory {

        private final AtomicInteger id = new AtomicInteger(0);

        private String name;

        public NameThreadFactory(String name) {
            this.name = name;
        }

        @Override
        public Thread newThread(Runnable r) {
            String threadName = name + id.getAndIncrement();
            Thread thread = new Thread(r, threadName);
            thread.setDaemon(true);
            return thread;
        }
    }
}
